package catchnthrow;

public class PI {
//	private PIGUI GUI;
	private PIParameters p;
	private double y, yref, I, v;

	public PI(String name, PIParameters params) {
		setParameters(params);
//		GUI = new PIGUI(this, params, name);
	}

	public synchronized double calculateOutput(double y, double yref) {
		this.y = y;
		this.yref = yref;
		v = p.K*(p.Beta*yref - y);
		if (p.integratorOn) {
			v = v + I;
		}
		return v;
	}

	public synchronized void updateState(double u) {
		if (p.integratorOn) {
			I = I + p.H*p.K/p.Ti*(yref - y) + p.H*(1/p.Tr)*(u - v);
		} else {
			I = 0.0;
		}
	}

	public synchronized long getHMillis() {
		return (long)(p.H*1000.0); //Sampling interval in milliseconds
	}

	public synchronized void setParameters(PIParameters newParameters) {
		p = (PIParameters)newParameters.clone();
	}

	/*
	 * Sets the I-part of the controller to 0. Needed when changing controller mode, e.g., from BEAM to BALL. 
	 */
	public synchronized void reset() {
		I = 0.0;
	}

	/*
	 * Returns the current PIParameters.
	 */
	public synchronized PIParameters getParameters(){
		return p;
	}

}

